package com.zm.spring.aop.Proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

//基于接口实现
public class JDKProxy {
    public static void main(String[] args) {
        人 person = new 房东();
        人 proxyObject = proxy(person);
        proxyObject.say();
    }
    public static <T> T proxy(T target){
        Object proxyObject = Proxy.newProxyInstance(
                target.getClass().getClassLoader(),
                target.getClass().getInterfaces(),
                new InvocationHandler() {
                    @Override
                    public Object invoke(
                            Object proxy,   //代理对象
                            Method method,  //方法对象
                            Object[] args   //参数数组
                    ) throws Throwable {
                        try {
                            System.out.println("前置增强");
                            Object ret = method.invoke(target, args);
                            System.out.println("返回增强");
                            return ret;
                        } catch (Exception e) {
                            System.out.println("异常增强");
                            throw new RuntimeException(e);
                        } finally {
                            System.out.println("后置增强");
                        }
                    }
                }
        );
        return (T) proxyObject;
    }
}
